using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.Net.Http;

namespace iqiyiApp
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        const string file_path = "E:/testweb.txt";
        const string file_hls_path = "E:/testweb.m3u8";

        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //GetWebData(); 
            GetFileByM3U8();
        }

        private void GetFileByM3U8() 
        {
            string fileStr = File.ReadAllText(file_hls_path);
            string[] file_arr = fileStr.Split(new char[] { '\n' } , StringSplitOptions.RemoveEmptyEntries);

            //List<string> url_lists = new List<string>();
            //foreach (string fi in file_arr)
            //{
            //    if (!fi.StartsWith("#EXT"))
            //    {
            //        url_lists.Add(fi);
            //    }
            //}
            List<string> url_lists = file_arr.Where(s => !s.StartsWith("#EXT")).ToList();

            HashSet<string> ts_files_hash = new HashSet<string>();
            Dictionary<string, List<string>> ts_dic = new Dictionary<string, List<string>>();

            bool isadd ;
            foreach (string u in url_lists)
            {
                string ts_1 = u.Split('?')[0];
                string ts_2 = ts_1.Split('/').Last();
                string ts_hash = ts_2.Split('.')[0];
                isadd = ts_files_hash.Add(ts_hash);
                if (isadd)
                {
                    ts_dic.Add(ts_hash, new List<string>());
                    ts_dic[ts_hash].Add(u);
                }
                else
                {
                    ts_dic[ts_hash].Add(u);
                }
                Console.WriteLine();
            }
            foreach (string file_hash in ts_files_hash)
            {
                string dl_file_name = file_hash + ".ts";
                List<string> dl_file_urls = ts_dic[file_hash];
                if (File.Exists(dl_file_name)) 
                {
                    File.Delete(dl_file_name);
                }
                Console.WriteLine();
                
                HttpClient hc = new HttpClient();
                FileStream fs = new FileStream(dl_file_name,FileMode.CreateNew,FileAccess.ReadWrite);
                foreach (var dl_url in dl_file_urls)
                {
                    byte[] webbytes = hc.GetByteArrayAsync(dl_url).Result;
                    fs.Write(webbytes, 0, webbytes.Length);
                }
                fs.Close();
                fs.Dispose();
                File.AppendAllText("dlm3u8.log", dl_file_name + "\t" + DateTime.Now.ToString()+ "\n");

                Console.WriteLine();
            }


            Console.WriteLine();
        }

        public void GetWebData() 
        {
            //https://cache.video.iqiyi.com/dash?tvid=8617404100&bid=610&vid=61121fa66bb2b3a69e4c596773605a14&src=01010031010000000000&vt=0&rs=1&uid=2415808695&ori=pcw&ps=0&k_uid=e71c00960d0baa067ce0946cc941a8c0&pt=0&d=0&s=&lid=&cf=&ct=&authKey=bf363c57c1dbc14764bfba04149d6908&k_tag=1&ost=0&ppt=0&dfp=a046e0b7aaf0e44241aaf49fafd859b2d377c504d597981ca0ffdde0f1576b1acf&locale=zh_cn&prio=%7B%22ff%22%3A%22f4v%22%2C%22code%22%3A2%7D&pck=ccm2oArhPsK7qYEQm1G2OJm3FopegyHdU3qs0JyzScbe4grBdkHGAu5aU1PKuPPYuTwla66&k_err_retries=0&up=&qd_v=2&tm=1571596870120&qdy=a&qds=0&k_ft1=143486267424772&k_ft4=68689924&k_ft5=1&bop=%7B%22version%22%3A%2210.0%22%2C%22dfp%22%3A%22a046e0b7aaf0e44241aaf49fafd859b2d377c504d597981ca0ffdde0f1576b1acf%22%7D&ut=1&vf=6a7ec1bb6bc7e28ad1df76f4649c8542

            string urlstr = "https://cache.video.iqiyi.com/dash?tvid=8617404100&bid=610&vid=61121fa66bb2b3a69e4c596773605a14&src=01010031010000000000&vt=0&rs=1&uid=2415808695&ori=pcw&ps=0&k_uid=e71c00960d0baa067ce0946cc941a8c0&pt=0&d=0&s=&lid=&cf=&ct=&authKey=bf363c57c1dbc14764bfba04149d6908&k_tag=1&ost=0&ppt=0&dfp=a046e0b7aaf0e44241aaf49fafd859b2d377c504d597981ca0ffdde0f1576b1acf&locale=zh_cn&prio=%7B%22ff%22%3A%22f4v%22%2C%22code%22%3A2%7D&pck=ccm2oArhPsK7qYEQm1G2OJm3FopegyHdU3qs0JyzScbe4grBdkHGAu5aU1PKuPPYuTwla66&k_err_retries=0&up=&qd_v=2&tm=1571596870120&qdy=a&qds=0&k_ft1=143486267424772&k_ft4=68689924&k_ft5=1&bop=%7B%22version%22%3A%2210.0%22%2C%22dfp%22%3A%22a046e0b7aaf0e44241aaf49fafd859b2d377c504d597981ca0ffdde0f1576b1acf%22%7D&ut=1&vf=6a7ec1bb6bc7e28ad1df76f4649c8542";

            string uastr = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36";
            HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(urlstr);
            //httpRequest.AllowAutoRedirect = false;
            //httpRequest.Timeout = 2000;
            httpRequest.UserAgent = uastr;
            //httpRequest.KeepAlive = true;
            HttpWebResponse response = (HttpWebResponse)httpRequest.GetResponse();
            Stream responseStream = response.GetResponseStream();
            StreamReader readStream = new StreamReader(responseStream);
            string allstr = readStream.ReadToEnd();
            byte[] allbyte = Encoding.UTF8.GetBytes(allstr);
            //File.WriteAllText(file_path, allstr);
            File.WriteAllBytes(file_path, allbyte);

            //#EXTM3U
            //#EXT-X-ENDLIST
            int a = allstr.IndexOf("#EXTM3U");
            int b = allstr.IndexOf("#EXT-X-ENDLIST");
            int c = allstr.LastIndexOf("#EXT-X-ENDLIST");

            //MemoryStream ms = new MemoryStream(bytes);
            var sub_str = allstr.Substring(a, b - a + 16);

            sub_str = sub_str.Replace(@"\/", "/");
            sub_str = sub_str.Replace(@"\n", "\n");
            File.WriteAllText(file_hls_path, sub_str);
            Console.WriteLine();

            //FileStream fs = new FileStream(file_path, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            //ms.WriteTo(fs);
            //fs.Flush();
            //fs.Close();

            #region 通过
            //MemoryStream ms = new MemoryStream(webbytes);
            //webbytes = null;
            //webbytes = new byte[ms.Length];
            //ms.Read(webbytes, 0, webbytes.Length);
            #endregion

            //#EXTM3U
            //#EXT-X-ENDLIST


        }


    }
}
